﻿
#include "qhalconwind.h"
#include "ui_qhalconwind.h"
#include <QFileDialog>
#include <QPainter>
#include <QWheelEvent>

QHalconWind::QHalconWind(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QHalconWind)
{
    ui->setupUi(this);

    //打开halcon 窗体
    Hlong WinIDcurrent = (Hlong)ui->HalconWinD->winId();
    HalconCpp:: OpenWindow(0,0,400,300,WinIDcurrent,"","",&htWindowHandle);


    ui->HalconWinD->installEventFilter(this);
    mIsDraw=false;
}




bool QHalconWind::eventFilter(QObject *obj, QEvent *event)
{

    if(!hoImage.IsInitialized())//判断图片是否存在
        return true;

    if(mIsDraw)
        return true;

    if(obj==ui->HalconWinD)
    {
        if(event->type()==QEvent::Enter)
        {

            try {
                HalconCpp::GetMposition(htWindowHandle,&htMouseRow,&htMouseCol,&htButton);
            } catch (...) {
                return true;
            }

            if(last_hvButton!=htButton)
            {
                last_hvButton=htButton;//鼠标变化了
                if(htButton.D()==0)// 鼠标释放
                {
                    m_bIsMove=false;
                }

                if(htButton.D()==1)// 左键按下
                {
                    last_hvMouseRow=htMouseRow;//记录鼠标按下时位置
                    last_hvMouseCol=htMouseCol;
                    m_bIsMove=true;
                }

                if(htButton.D()==4)// 右键按下
                {
                    m_bIsMove=false;
                }

                return true;

            }

            //仿造为鼠标移动
            //QMouseEvent *mouseE=(QMouseEvent*)event;
            //QMouseEvent fake((QEvent::MouseMove),QPoint(mouseE->pos().x(),mouseE->pos().y()),Qt::NoButton,Qt::NoButton, Qt::NoModifier);

            this->LabelMouseMoveEvent();
            return true;


        }
    }

    return false;
}






void QHalconWind::LabelMouseMoveEvent()
{


    if(m_bIsMove)
    {
        try {
            //计算移动值
            move_hvMouseRow=htMouseRow-last_hvMouseRow;
            move_hvMouseCol=htMouseCol-last_hvMouseCol;
            //获取当前的窗口坐标
            HalconCpp::GetPart(htWindowHandle,&startRowBf,&startColBf,&endRowBf,&endColBf);

            HalconCpp:: SetPart(htWindowHandle,startRowBf-move_hvMouseRow,startColBf - move_hvMouseCol, endRowBf - move_hvMouseRow, endColBf - move_hvMouseCol);

            HalconCpp::AttachBackgroundToWindow(hoImage,htWindowHandle);

        } catch (...) {
        }


        return;
    }

    //获取灰度值
    HTuple pointGray;
    try
    {
        GetGrayval(hoImage, htMouseRow, htMouseCol, &pointGray);
    }
    catch (HException)
    {
        ui->lbStatus->setText("");

        return;
    }

    //设置坐标
    //    ui->lbStatus->setText(QString::fromLocal8Bit("X坐标：%1    Y坐标：%2    灰度值：%3").arg(htMouseCol[0].D()).arg(htMouseRow.ToSArr()->ToLocal8bit()).arg(pointGray.ToSArr()->ToLocal8bit()));


    if(pointGray.Length()==1)
    {
        ui->lbStatus->setText(QString::fromLocal8Bit("X坐标：%1    Y坐标：%2    灰度值：%3").arg(htMouseCol[0].I()).arg(htMouseRow[0].I()).arg(pointGray[0].I()));
    }
    else {
        ui->lbStatus->setText(
                    QString::fromLocal8Bit("XY:[ %1 , %2 ] GV：[ %3 , %4 , %5 ]")
                    .arg(htMouseCol[0].I())
                .arg(htMouseRow[0].I())
                .arg(pointGray[0].I())
                .arg(pointGray[1].I())
                .arg(pointGray[2].I())
                );

    }

}




void QHalconWind::wheelEvent(QWheelEvent *event)
{


    // event->delta() is a multiple of 120. For larger multiples, the user
    // rotated the wheel by multiple notches.
    int num_notch = std::abs(event->delta()) / 120;
    double factor = (event->delta() > 0) ? std::sqrt(2.0) : 1.0 / std::sqrt(2.0);
    while (num_notch > 1)
    {
        factor = factor * ((event->delta() > 0) ? std::sqrt(2.0) : 1.0 / std::sqrt(2.0));
        num_notch--;
    }

    // get zooming center

    HTuple hv_centerRow,hv_centerCol;
    double centerRow, centerCol;

    HalconCpp::ConvertCoordinatesWindowToImage(htWindowHandle,event->y(), event->x(), &hv_centerRow, &hv_centerCol);

    centerRow=hv_centerRow.D();

    centerCol=hv_centerCol.D();
    // get current image part
    double row1, col1, row2, col2;
    GetPartFloat(&row1, &col1, &row2, &col2);
    // zoom around center
    double left = centerRow - row1;
    double right = row2 - centerRow;
    double top = centerCol - col1;
    double buttom = col2 - centerCol;
    double newRow1 = centerRow - left * factor;
    double newRow2 = centerRow + right * factor;
    double newCol1 = centerCol - top * factor;
    double newCol2 = centerCol + buttom * factor;
    try
    {

        HalconCpp::SetPart(htWindowHandle,newRow1,newCol1, newRow2, newCol2);


        HalconCpp::ClearWindow(htWindowHandle);

        if(hoImage.IsInitialized())
        {
            HalconCpp::DispObj(hoImage,htWindowHandle);
        }
    }
    catch (HalconCpp::HOperatorException)
    {
        // this may happen, if the part is much too small or too big
    }
}



void QHalconWind::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);

    htWindWidth = ui->HalconWinD->size().width();
    htWindHeight = ui->HalconWinD->size().height();
    if(hoImage.IsInitialized())
    {
        calWH();
        //计算横纵比例
        SetPart(htWindowHandle,0,0,htHeight,htWidth);
        DispObj(hoImage,htWindowHandle);
    }
    else {
        //改变窗体大小
        HalconCpp::SetWindowExtents(htWindowHandle,0,0,htWindWidth,htWindHeight);
    }

}

void QHalconWind::GetPartFloat(double *row1, double *col1, double *row2, double *col2)
{
    // to get float values from get_part, use HTuple parameters
    HalconCpp::HTuple trow1, tcol1, trow2, tcol2;
    HalconCpp::GetPart(htWindowHandle,&trow1, &tcol1, &trow2, &tcol2);
    *row1 = trow1.D();
    *col1 = tcol1.D();
    *row2 = trow2.D();
    *col2 = tcol2.D();
}

void QHalconWind::calWH()
{

    double wh=htWidth.D()/htHeight.D()*htWindHeight;

    if(wh<=htWindWidth)
    {
        //改变窗体大小
        HalconCpp::SetWindowExtents(htWindowHandle,0,0,wh,htWindHeight);
    }
    else {

        wh=htHeight.D()/htWidth*htWindWidth;
        HalconCpp::SetWindowExtents(htWindowHandle,0,0,htWindWidth,wh);
    }
}

QHalconWind::~QHalconWind()
{
    delete ui;
}


void QHalconWind::on_tb1Pic_clicked()
{
    QString imagePath = QFileDialog::getOpenFileName(this, tr("Open image"), "",
                                                     tr("All Images (*.bmp *.tif *.jpg);;"
                                                        "Image bmp (*.bmp);;"
                                                        "Image tif (*.tif);;"
                                                        "Image jpg (*.jpg);;"
                                                        ));

    if(imagePath.isEmpty())
        return;

    if(hoImage.IsInitialized())
    {
        HalconCpp::GenEmptyObj(&hoImage);
    }



    ReadImage(&hoImage,reinterpret_cast<const wchar_t *>(imagePath.utf16()));
    GetImageSize(hoImage,&htWidth,&htHeight);

    calWH();
    SetPart(htWindowHandle,0,0,htHeight,htWidth);

    DispObj(hoImage,htWindowHandle);
}

void QHalconWind::on_tb2Reset_clicked()
{
    if(!hoImage.IsInitialized())
        return;

    calWH();
    SetPart(htWindowHandle,0,0,htHeight,htWidth);

    DispObj(hoImage,htWindowHandle);

}

void QHalconWind::on_tb3Circle_clicked()
{
    if(!hoImage.IsInitialized())
        return;

    m_bIsMove=false;
    mIsDraw=true;
    HTuple Row,  Column,  Radius;
    HalconCpp::DrawCircle(htWindowHandle,&Row,  &Column,  &Radius);
    mIsDraw=false;
}



void QHalconWind::on_tb4Rect1_clicked()
{
    if(!hoImage.IsInitialized())
        return;

    m_bIsMove=false;
    mIsDraw=true;
    HTuple Row1,  Column1, Row2, Column2;
    HalconCpp::DrawRectangle1(htWindowHandle,&Row1,  &Column1, &Row2, &Column2);

    mIsDraw=false;
}

void QHalconWind::on_tb5Rect2_clicked()
{
    if(!hoImage.IsInitialized())
        return;

    m_bIsMove=false;
    mIsDraw=true;
    HTuple Row1,  Column1,Phi, Row2, Column2;
    HalconCpp::DrawRectangle2(htWindowHandle,&Row1,  &Column1,&Phi, &Row2, &Column2);
    mIsDraw=false;
}
